from django.shortcuts import render
from django.shortcuts import redirect
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from datetime import datetime
import hashlib
from django.core.paginator import Paginator
from common.models import Users,Types,Goods

# Create your views here.

# 商品导航信息加载
def loadPNav(request):
    '''商品导航信息加载'''
    context={}
    plists=Types.objects.filter(pid=0)
    context["typelist"]=plists
    return context

# 查询服装类最新商品
def getClothNewGoods(request,goodslist):
    parentctypes=Types.objects.get(name='服装')# 服装分类ID
    ctypes=Types.objects.filter(pid=parentctypes.id)# 服装子分类
    ctypesids=[]
    for t in ctypes:
        ctypesids.append(t.id)
    clothlist=goodslist.filter(typeid__in=ctypesids)
    newClothList=clothlist.order_by("-addtime")[0:5]
    return newClothList

# 查询数码 类最新商品
def getDigitNewGoods(request,goodslist):
    parenttypes=Types.objects.get(name='数码')# 数码分类ID
    dtypes=Types.objects.filter(pid=parenttypes.id)# 数码子分类
    dtypesids=[]
    for t in dtypes:
        dtypesids.append(t.id)
    # print("数码子分类",dtypesids)
    digitlist=goodslist.filter(typeid__in=dtypesids)
    newDigitList=digitlist.order_by("-addtime")[0:5]
    return newDigitList


def index(request):
    '''商城首页'''
    context = loadPNav(request)
    goodslist=Goods.objects.filter(state=1)
    # 热卖商品
    hotlist=goodslist.order_by("-clicknum")[0:5]
    # print("热卖商品",hotlist)

    # 最新数码
    newDigitList=getDigitNewGoods(request,goodslist)
    # 最新服装
    newClothList=getClothNewGoods(request,goodslist)

    context["hotlist"]=hotlist
    context["newDigitList"]=newDigitList
    context["newClothList"]=newClothList
    return render(request,"web/index.html",context)

def plist(request,page=1):
    '''商品列表页'''
    # 加载公共一级分类导航
    context=loadPNav(request)
    # 商品信息查询
    mywhere=[] # 搜索条件
    mod=Goods.objects
    typeid=int(request.GET.get("tid",0))# 一级分类
    if typeid>0:
        # 根据分类查询
        goodsData=mod.filter(typeid__in=Types.objects.only('id').filter(pid=typeid))
        mywhere.append('tid=' + str(typeid))
    else:
        # 查询所有分类
        goodsData=mod.filter()
    # 关键字搜索
    kw=request.GET.get("kw",None)
    if kw:
        goodsData=goodsData.filter(goods__contain=kw)
        mywhere.append("kw="+kw)
    # 分页信息
    page=int(page)# 当前页码
    pagelist = []  # 页码
    p = Paginator(goodsData, 8)
    maxpage=p.num_pages# 最大页数
    if page is None or page == '' or page<1:
        page = 1
    elif page>maxpage:
        page=maxpage
    page = int(page)
    goodsData2 = p.page(page)
    pagelist = p.page_range
    context["goodslist"]=goodsData2
    context["tid"] = typeid
    context["mywhere"] = mywhere
    context["pagelist"] = pagelist
    context["page"] = page
    return render(request,"web/plist.html",context)

def pdetail(request,pid):
    '''商品详情页'''
    # 加载公共一级分类导航
    context = loadPNav(request)
    # 根据商品ID获取商品详情
    goodsinfo=Goods.objects.get(id=pid)
    goodsinfo.clicknum+=1 # 点击量加1
    goodsinfo.save()
    context["goods"]=goodsinfo
    return render(request,"web/pdetail.html",context)

#------会员登陆------
def login(request):
    '''会员登陆'''
    return render(request,'web/login.html')
def dologin(request):
    '''执行登陆'''
    try:
        # 验证码检查
        verifycode = request.session['verifycode']
        code = request.POST['code']
        if verifycode.lower() != code.lower():
            context = {'info': '验证码错误！'}
        else:
            username=request.POST["username"]
            if username is None or username=="":
                context = {'info': '请输入登陆账户！'}
            else:
            # 根据用户名获取登陆信息
                uobj = Users.objects.get(username=username)
                if uobj.state==0 or uobj.state==1:
                    m=hashlib.md5()
                    pwd=request.POST["password"]
                    m.update(bytes(pwd,encoding='utf8'))
                    # 密码正确，则登陆成功，将登陆信息保存在session,并跳转首页
                    if uobj.password==m.hexdigest():
                        request.session["vipuser"] = uobj.toDict()
                        return redirect(reverse('index'))
                    else:
                        context = {"info": "登陆密码错误！"}
                else:
                    context = {"info": "该用户被禁用！"}
    except Exception as err:
        context={"info":"登陆异常！"}
    return render(request,'web/login.html',context)
def logout(request):
    '''退出登陆'''
    del request.session['vipuser']# 清除本地缓存登陆信息
    return redirect(reverse('login'))

# ----会员注册----
def register(request):
    '''会员注册'''
    return render(request,'web/register.html')
def doregister(request):
    '''执行注册'''
    try:
        uobj=Users()
        uobj.username=request.POST["reg_username"]
        pwd = request.POST["reg_pwd"]  # 密码
        repwd = request.POST["reg_repwd"]  # 重复密码
        if uobj.username is None or uobj.username=="":
            context = {"info": "请输入登陆账户！"}
        elif pwd!=repwd:
            context = {"info": "两次输入密码不一致！"}
        else:
            m=hashlib.md5()
            m.update(bytes(pwd,encoding='utf8'))
            uobj.password=m.hexdigest()
            uobj.state = 1 # 普通会员
            uobj.addtime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            uobj.save()
            context = {"info": "注册成功，请登陆！","status":"success"}
            return render(request, 'web/login.html', context)
    except Exception as err:
        print(err)
        context={"info":"注册异常！"}
    return render(request,'web/register.html',context)